package com.wkbb.basic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.config.BasicConfig;
import com.wkbb.basic.constant.BasicConstants;
import com.wkbb.basic.feign.DoorFeignService;
import com.wkbb.basic.feign.TcCloudFeignService;
import com.wkbb.basic.feign.WxFeignService;
import com.wkbb.basic.mapper.EmployeeMapper;
import com.wkbb.basic.mapper.OrganizationMapper;
import com.wkbb.basic.mapper.SysRoleUserMapper;
import com.wkbb.basic.mapper.UserInfoMapper;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.*;
import com.wkbb.basic.thread.SynOrgAccessInitTask;
import com.wkbb.basic.thread.UpdateOrgUserRedisTask;
import com.wkbb.basic.utils.FillEmptyHeadImgUtil;
import com.wkbb.basic.utils.WebankUtil;
import com.wkbb.basic.vo.TeacherManageVo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.business.BasicBusiness;
import com.wkbb.common.config.ServiceConfig;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.AccountOrgDto;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.dto.basic.OrganizationDto;
import com.wkbb.common.dto.wx.AccountDto;
import com.wkbb.common.enums.*;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.wkbb.basic.constant.BasicConstants.DEFAULT_HEADIMG_TEACHER_MALE;

/**
 * @author Lilin
 */
@Service
@Slf4j
public class OrganizationServiceImpl extends BaseServiceImpl<Organization> implements OrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private WxFeignService wxFeignService;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private ClassInfoService classInfoService;

    @Autowired
    private TcCloudFeignService tcCloudFeignService;

    @Autowired
    private DoorFeignService doorFeignService;

    @Autowired
    private OrganizationWebankService organizationWebankService;

    @Autowired
    private WebankUtilService webankUtilService;

    @Autowired
    private UserService userService;

    @Autowired
    private ServiceConfig serviceConfig;

    @Autowired
    private BasicConfig basicConfig;

    @Autowired
    public void setMapper(OrganizationMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public OrganizationDto getInfo(Long id) {
        return organizationMapper.getOrgInfoById(id);
    }

    @Override
    public List<OrganizationDto> getList(Map<String, Object> params) {
        return organizationMapper.getOrgInfoList(params);
    }

    @Override
    public PageInfo<OrganizationDto> getPage(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<OrganizationDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<OrganizationDto> pageInfo = new PageInfo<>(organizationMapper.getOrgInfoList(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    public Organization getByPrimaryKey(Long id) throws Exception {
        //先查缓存
        String key = BasicBusiness.getOrganizationRedisKey(id);
        Organization organization = null;
        try {
            organization = (Organization) redisTemplateUtil.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //若缓存没有，到数据库查
        if (organization == null) {
            organization = super.getByPrimaryKey(id);
            try {
                //添加到缓存
                redisTemplateUtil.set(key, organization);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return organization;
    }

    @Override
    public PageInfo<Agent> getAgentListByPage(Map<String, Object> params, int pageNo, int pageSize) {
        Page<Agent> page = PageHelper.startPage(pageNo, pageSize,true);
        List<Agent>  list = organizationMapper.getAgentList(params);
        PageInfo<Agent> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    public Agent getAgentById(Integer id) {
        return organizationMapper.getAgentById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<Long> insertAgent(Agent data) throws Exception{
        //添加机构
        Organization organization = new Organization();
        BeanUtil.applyIf(organization,data);
        organization.setTypeSet(TypeSetEnum.STATE_RUN.getValue());
        organization.setOrigin(OriginTypeEnum.SELF_SUPPORT.getValue());
        organization.setUpdateBy(organization.getCreateBy());
        organization.setOrgType(2);
        organization.setParentId(0L);
        organization.setStatus(true);

        Map<String, Object> params = new HashMap<>();
        params.put("organizationCode", data.getOrganizationCode());
        Agent oldA = organizationMapper.getOrganizationInfoByMapParams(params);
        if (oldA != null){
            return ResultDTO.errorResult("此机构编码已存在，请填入其他编码");
        }
        //判断该账号是否存在
        params.put("account", data.getAccount());
        Employee oldData = employeeMapper.getByMapParams(params);
        if (oldData != null){
            return new ResultDTO<>(ErrorCode.ACCOUNT_HAS_REGISTER);
        }

        //添加机构
        organizationMapper.insert(organization);

        //添加代理商扩展信息
        data.setOrgId(organization.getId());
        organizationMapper.insertOrganizationInfo(data);

        //添加机构管理员账号
        Employee employee=new Employee();
        BeanUtil.applyIf(employee,organization);
        employee.setMobile(data.getContactPhone());
        employee.setOrgId(organization.getId());
        employee.setAccount(data.getAccount());
        employee.setPassword(data.getPassword());
        employee.setUserType((short) 2);

        //添加用户信息
        Object roleType = userService.updateRoleTypeJson(null, null, Short.parseShort("" + RoleTypeEnum.AGENT.getValue()), null, employee.getOrgId(),null);
        User user = new User();
        BeanUtil.applyIf(user ,organization);
        user.setName("机构管理员");
        user.setRoleType(roleType);
        user.setStatus(true);
        user.setHeadImgUrl(BasicConstants.DEFAULT_HEADIMG_TEACHER_MALE);
        user.setUserCode(UuIdUtil.getUserCodeByUUId());
        userService.insert(employee.getOrgId(), user, RoleTypeEnum.AGENT.getValue(), "男", employee.getUserType(),null,false);

        UserInfo userInfo = new UserInfo();
        BeanUtil.applyIf(userInfo, employee);
        userInfo.setUserId(user.getId());
        userInfo.setHeadImgMd5(userService.getImageMD5(user.getHeadImgUrl()));
        userInfo.setSpeakName(user.getName());
        userInfo.setProvinceCode(data.getProvinceId().toString());
        userInfo.setProvince(data.getProvince());
        userInfo.setCityCode(data.getCityId().toString());
        userInfo.setCity(data.getCity());
        userInfo.setSex("男");
        userInfo.setAreaCode(data.getAreaId().toString());
        userInfo.setArea(data.getArea());
        userInfo.setAddr(data.getAddress());
        userInfoMapper.insert(userInfo);

        employee.setUserId(user.getId());
        employee.setPassword(MD5Util.getMD5Code(employee.getPassword()));
        employee.setStatus(true);
        employeeMapper.insert(employee);

        //添加管理权限
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setOrgId(employee.getOrgId());
        sysRoleUser.setRoleId(5L);
        sysRoleUser.setUserId(user.getId());
        sysRoleUser.setCreateBy(employee.getCreateBy());
        sysRoleUser.setUpdateBy(employee.getCreateBy());
        sysRoleUserMapper.insert(sysRoleUser);
        return new ResultDTO<>(organization.getId());
    }


    @Override
    @Transactional
    public ResultDTO insertOrganization(Organization organization) throws Exception {

        super.insert(organization);

        //调微信开账户(代理商 教育局 集团自动开户)
       /* if(organization.getOrgType()==OrganizationTypeEnum.AGENT.getValue().intValue()
        ||organization.getOrgType()==OrganizationTypeEnum.EDUCATION.getValue().intValue()
        ||organization.getOrgType()==OrganizationTypeEnum.CONGLOMERATE.getValue().intValue()) {

            AccountDto accountDto = new AccountDto();

            accountDto.setGroupId(organization.getId());
            accountDto.setName(organization.getName());

            //组装组织列表
            List<AccountOrgDto> accountOrgList = new ArrayList<>();
            AccountOrgDto accountOrgDto = new AccountOrgDto();
            accountOrgDto.setOrgId(organization.getId());
            accountOrgDto.setOrgName(organization.getName());
            accountOrgList.add(accountOrgDto);

            accountDto.setOrgInfo(accountOrgList);

            wxFeignService.addAccount(accountDto);
        }*/

        if(!organization.getOrgType().equals(OrganizationTypeEnum.AGENT.getValue())){

            //添加到缓存
            String key = BasicBusiness.getOrganizationRedisKey(organization.getId());
            try {
                redisTemplateUtil.set(key, organization);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //如果为新增幼儿园则初始化学校考勤、通行权限信息
            /*if(organization.getOrgType().equals(OrganizationTypeEnum.KINDERGARTEN.getValue())){
                ThreadPoolUtil.addPoolTask(new SynOrgAccessInitTask(doorFeignService, organization.getId()));
            }*/
        }

        //开始申请APPID
       /* OrganizationWebank validOrganizationWebank = organizationWebankService.getValidOrganizationWebank();//取一个有用的webankappid用来调用申请appid的接口

        if (null == validOrganizationWebank) {
            log.info("----------没有可用微众appid----------");
            return new ResultDTO<>(ErrorCode.GET_VALID_WEBANK_CONFIG);
        }

        String appNo = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        int serviceType = serviceConfig.getProfilesActive().equals(ProfilesActiveEnum.PRO.getDesc()) ? 1 : 0;
//            short serviceType = 0;//0-试用版的 APPID            1-正式版的 APPID，二选一

        log.info("----------申请appid----------  basicConfig.getWebankOrgId():{},appNo:{}", basicConfig.getWebankOrgId(), appNo);
        String result = webankUtilService.getAPPID(appNo, true, validOrganizationWebank.getWebankAppid(), validOrganizationWebank.getWebankSecret(), organization.getId(), organization.getName(), (short) serviceType, basicConfig.getWebankOrgId());
        if (!WebankUtil.checkIfSuccess(result)) {//申请appid失败
            log.info("----------申请appid失败----------result:{}", result);
            return new ResultDTO<>(ErrorCode.ADD_WEBANK_CONFIG);
        }
        OrganizationWebank organizationWebank = new OrganizationWebank();
        organizationWebank.setOrgId(organization.getId());
        organizationWebank.setAppNo(appNo);
        organizationWebank.setServiceType((short) serviceType);
        organizationWebank.setStatus(Short.parseShort("0"));//未审核状态
        organizationWebankService.insert(organizationWebank);*/

        return new ResultDTO<>(organization.getId());
    }

    @Override
    public void update(Organization entity) throws Exception {
        update(entity, false);
    }


    @Override
    public ResultDTO update(Organization organization, boolean isBack) throws Exception {
        if (isBack) {
            //IM相关开始---------------------------学校设置负责人---------------------------
            Long orgId = organization.getId();
            Long newMasterId = organization.getMasterId();
            Long oriMasterId = organization.getOriMasterId();
            log.info("-----学校设置负责人-----orgId={},oriMasterId={},newMasterId={}",orgId,oriMasterId,newMasterId);
            if(null!=newMasterId){
                //判断设置的负责人是否是园长角色,如果不是园长则提示"非园长身份不能设置为负责人"
                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("orgId",orgId);
                paramMap.put("userId",newMasterId);
                Employee employee = employeeMapper.getByMapParams(paramMap);
                if (null != employee) {
                    Short userType = employee.getUserType();
                    log.info("-----学校设置负责人,新的负责人userType={}-----",userType);
                    if(userType != UserTypeEnum.MASTER.getValue().shortValue()&&organization.getOrgType().equals(OrganizationTypeEnum.KINDERGARTEN.getValue())){
                        return new ResultDTO(ErrorCode.MASTER_SELECTED_ERROR);
                    }
                    //这里有两种情况。1:指定负责人(原来负责人为空的情况),2:更换负责人(原来负责人不为空的情况)
                    //前端新增一个原负责人的字段oriMasterId,用来记录原负责人,原负责人在群聊中需要直接降级为管理员
                    //原负责人不等于新负责人的情况下才去调用IM
                    if (null != oriMasterId&&organization.getOrgType().equals(OrganizationTypeEnum.KINDERGARTEN.getValue())) {
                        if (newMasterId.longValue() != oriMasterId.longValue()) {
                            //2:更换负责人,若更换了负责人，不退群,转让群主；
                            //2.1新负责人进入所有群担任群主一职
                            log.info("----学校设置负责人----不退群,转让群主。更换负责人开始------");
                            classInfoService.makeOverGroup(newMasterId,orgId,oriMasterId);
                            log.info("----学校设置负责人----不退群,转让群主。更换负责人结束------");
                        }
                    }

                    if(organization.getOrgType().equals(OrganizationTypeEnum.KINDERGARTEN.getValue())){
                        //1:指定负责人
                        //开始调用IM-新负责人入全校班级群接口,并担任全部班级群主群(这个接口分成2个接口来调)
                        //拉取所有非学校负责人的园长入群
                        log.info("----学校设置负责人----拉取所有非学校负责人的园长入群。拉取开始------orgId={}",orgId);
                        classInfoService.saveAutoGroupUserMaster(orgId,UserTypeEnum.MASTER.getValue().shortValue(),null,null,null);
                        log.info("----学校设置负责人----拉取所有非学校负责人的园长入群。拉取结束------");
                        tcCloudFeignService.setMasterGroup(orgId,newMasterId, (short)RoleTypeEnum.TEACHER.getValue(),UserTypeEnum.MASTER.getValue().shortValue(), ImGroupTypeEnum.AUTOGROUP.getValue().shortValue());
                    }
                }
            }

            //如果修改学校名称，同步名称到账户信息
            try {
                if (organization.getOrgType() > OrganizationTypeEnum.CONGLOMERATE.getValue().intValue()) {
                    Organization orignOrganization = organizationMapper.getByPrimaryKey(organization.getId());
                    if (!orignOrganization.getName().equals(organization.getName())) {
                        log.info("*****有修改学校名称，同步到账户信息******");
                        OrganizationDto organizationDto = new OrganizationDto();
                        organizationDto.setId(organization.getId());
                        organizationDto.setName(organization.getName());
                        wxFeignService.updateAccountOrgInfo(organizationDto);

                        //异步更新用户redis
                        UpdateOrgUserRedisTask updateOrgUserRedisTask = new UpdateOrgUserRedisTask(userService,organization.getId());
                        ThreadPoolUtil.addPoolTask(updateOrgUserRedisTask);
                    }
                }
            }
            catch (Exception e)
            {
                log.error("********同步名称到账户信息异常*******",e);
            }

            //IM相关结束---------------------------学校设置负责人---------------------------
            organizationMapper.updateBack(organization);


        } else {
            super.update(organization);
        }

//        OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(organization.getId(),null);
//        if(null!=organizationWebank){
//            //报备微众后台
//            webankUtilService.modifyGroup(organization.getId().toString(), organization.getName(), 1, null, false,organizationWebank.getWebankAppid(),organizationWebank.getWebankSecret(),organization.getId());
//        }

        //修改缓存
        String key = BasicBusiness.getOrganizationRedisKey(organization.getId());
        try {
            redisTemplateUtil.set(key, super.getByPrimaryKey(organization.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO();
    }


    @Override
    public List<AccountOrgDto> getAccountOrgList(Long accountId) {
        List<AccountOrgDto> organizationList = new ArrayList<AccountOrgDto>();
        //查询账户信息
        ResultDTO<AccountDto> accountDtoResult = wxFeignService.getAccount(accountId);
        if (accountDtoResult.isSuccess() && null != accountDtoResult.getData()) {
            AccountDto accountDto = (AccountDto) accountDtoResult.getData();
            Object orgInfoObj = accountDto.getOrgInfo();
            if (null != orgInfoObj) {
                organizationList = JSONObject.parseArray(JSON.toJSONString(orgInfoObj), AccountOrgDto.class);
            }
        }
        return organizationList;
    }

    @Override
    public Organization getOrgByAccount(Long accountId) {
        //先从redis中获取
        List<AccountOrgDto> organizationList = getAccountOrgList(accountId);
        if (null == organizationList || organizationList.size() == 0) {
            return null;
        }
        Long orgId = organizationList.get(0).getOrgId();
        Organization organization = organizationMapper.getByPrimaryKey(orgId);
        if (organizationList.size() > 1) {
            //集团园
            if (null != organization) {
                Organization parentOrganization = organizationMapper.getByPrimaryKey(organization.getParentId());
                return parentOrganization;
            }
        }
        return organization;
    }

    @Override
    public List<OrganizationDto> getNewOrgListByOldIds(List<Long> oldOrgIds) {
        return organizationMapper.getNewOrgListByOldIds(oldOrgIds);
    }

    @Override
    public PageInfo<OrganizationDto> getOrgListByPage(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<OrganizationDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<OrganizationDto> pageInfo = new PageInfo<OrganizationDto>(organizationMapper.getOrgListByPage(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    public OrganizationDto getAgentInfoByUserId(Long userId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        //获取代理商信息
        return organizationMapper.getAgentInfoByUserId(params);
    }

    @Override
    public OrganizationDto getOrgInfoByUserId(Long userId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        //获取学校信息
        return organizationMapper.getOrgInfoByUserId(params);
    }

	@Override
    public Organization getOrgByOldOrgId(Long oldOrgId) {
        return organizationMapper.getNewOrgByOld(oldOrgId);
    }

    /**
     * //根据name来查询
     * @param orgType
     * @param orgName
     * @return
     */
    @Override
    public Organization getOrgByName(Integer orgType, String orgName) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", orgName);
//        paramMap.put("status", 1);
//        paramMap.put("orgType", orgType);
        return organizationMapper.getByMapParams(paramMap);
    }

    @Override
    public List<Map<String, Object>> getOrgCountByType(OrganizationDto organizationDto) {
        List<Organization> educationList = getEducationList(OrganizationTypeEnum.EDUCATION.getValue(), organizationDto);
        Map<String, Object> paramsMap = getParamsMap(educationList);
        return organizationMapper.getOrgCountByType(paramsMap);
    }

    @Override
    public List<Organization> getEducationList(Integer orgType, OrganizationDto organizationDto) {
        List<Organization> orgList = new ArrayList<Organization>();

        //添加
        Organization organization = new Organization();
        BeanUtils.copyProperties(organizationDto, organization);
        orgList.add(organization);

        //查询是否有下级
        Map<String, Object> orgParams = new HashMap<>();
        orgParams.put("parentId", organizationDto.getId());
        List<Organization> childList = organizationMapper.getListByMapParams(orgParams);
        orgList.addAll(childList);
        if (childList.size() > 0) {
            this.recursiveOrganization(orgList, orgType, childList);
        }

        return orgList;
    }

    //递归查询子代理商
    @Override
    public void recursiveOrganization(List<Organization> orgList,Integer orgType,List<Organization> organizationList)
    {
        for(Organization organization : organizationList) {
            Map<String, Object> params = new HashMap<>(1);
            params.put("orgType", orgType);
            params.put("parentId", organization.getId());

            List<Organization> list = organizationMapper.getListByMapParams(params);
            orgList.addAll(list);

            this.recursiveOrganization(orgList,orgType,list);
        }
    }

    /**
     * 获取教育局下全部学校
     * @return
     */
    @Override
    public List<Organization> getOrganizationList(OrganizationDto organizationDto) {
        List<Organization> educationList = getEducationList(OrganizationTypeEnum.EDUCATION.getValue(),organizationDto);
        Map<String,Object> paramsMap = getParamsMap(educationList);
        List<Organization> organizationList = organizationMapper.getListByMapParams(paramsMap);
        return organizationList;
    }

    private Map<String,Object> getParamsMap(List<Organization> educationList){
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("orgType", OrganizationTypeEnum.KINDERGARTEN.getValue());
        paramsMap.put("origin", OriginTypeEnum.SELF_SUPPORT.getValue());
        if(CollectionUtils.isNotEmpty(educationList)) {
            paramsMap.put("educationIds", educationList);
        }
        paramsMap.put("status",1);
        return paramsMap;
    }

    @Override
    @Transactional
    public void deleteById(Long orgId) {
        organizationMapper.deleteById(orgId);
    }

    @Override
    public List<Map<String, Object>> getOrgCountStatByOrgan(Map<String, Object> params)
    {
        return organizationMapper.getOrgCountStatByOrgan(params);
    }

    @Override
    public List<Map<String, Object>> getOrgListByOrgan(Map<String, Object> params)
    {
        return organizationMapper.getOrgListByOrgan(params);
    }

    @Override
    public List<Map<String, Object>> getOrgDataStat(Map<String, Object> params)
    {
        return organizationMapper.getOrgDataStat(params);
    }

    /**
     * 查询所有申请中的APPID申请结果并绑定用户组
     */
    @Override
    public void searchAPPID(String webankAppid,String webankSecret,Long orgId , String webankOrgId ) {
        List<OrganizationWebank> organizationWebankList = organizationWebankService.getOrganizationWebanksInProgress();
        organizationWebankList.forEach(organizationWebank -> {
            String rs = webankUtilService.searchAPPID(organizationWebank.getAppNo(), true, webankAppid, webankSecret, orgId ,webankOrgId);
//                    {"code":"0","msg":"请求成功","bizSeqNo":"2008052AA03490400119312936681984","result":{"serviceType":"1","appName":"测试获取appid",
//                            "appNo":"12855F60639B4C2490FDEFB43D96F65F","reviewStatus":"0","orgId":"34920047"},"webankAppId":"IOTiT5Zw",
//                            "orderNo":"64f3b870-acda-4f84-94b9-dd4cd81a5e09","transactionTime":"20200805193129"}
            if (StringUtil.isEmpty(rs)) {
                log.info("======Webank======查询申请appid结果，失败：{}" + rs);

            } else {

                JSONObject jsonObject = JSON.parseObject(rs);
                String code = jsonObject.getString("code");

                String result = jsonObject.getString("result");
                JSONObject resultJson = JSON.parseObject(result);

                String appNo = resultJson.getString("appNo");
                String appName = resultJson.getString("appName");
                String reviewStatus = resultJson.getString("reviewStatus");//0-未审核 1-处理中 2-审核通过 3-驳回
                String appId = resultJson.getString("appId");
                String secret = resultJson.getString("secret");
                String effectDate = resultJson.getString("effectDate"); //appId 生效日期

                log.info("======Webank======查询申请appid结果:code:{},appNo：{}，reviewStatus：{}，appId：{}，effectDate：{}", code, appNo, reviewStatus, appId, effectDate);

                if (WebankUtil.CODE_SUCCESS.equals(code) && organizationWebank.getAppNo().equals(appNo)) {
                    if ("2".equals(reviewStatus) && StringUtil.isNotEmptyIgnoreBlank(appId) && StringUtil.isNotEmptyIgnoreBlank(secret)) {
                        organizationWebank.setWebankAppid(appId);
                        organizationWebank.setWebankSecret(secret);
                        organizationWebank.setStatus(Short.parseShort(reviewStatus));
                        try {
                            organizationWebankService.update(organizationWebank);
                            //绑定用户组
                            log.info("======Webank======绑定用户组");
                            String addGroupResult = webankUtilService.addGroup(organizationWebank.getOrgId().toString(), appName, 1, null, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), organizationWebank.getOrgId());
                            if (WebankUtil.checkIfSuccess(addGroupResult)) {
                                log.info("======Webank======绑定用户组 完成");
                            } else {
                                log.info("======Webank======绑定用户组 失败：{}" + addGroupResult);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        //0-未审核 1-处理中 3-驳回 或 appId和secret为空
                        organizationWebank.setStatus(Short.parseShort(reviewStatus));
                        try {
                            organizationWebankService.update(organizationWebank);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        );

    }

    /**
     * 查询城市下的学校
     * */
    @Override
    public List<OrganizationDto> getOrgListByCity(Long orgId)
    {
        Organization organization = organizationMapper.getByPrimaryKey(orgId);
        Integer provinceId = organization.getProvinceId();
        Integer cityId = organization.getCityId();
        if(null!=provinceId && null!=cityId)
        {
            Map<String, Object> params = new HashMap<>(1);
            params.put("orgType", organization.getOrgType());
            params.put("provinceId", provinceId);
            params.put("cityId", cityId);

            return organizationMapper.getOrgListByCity(params);
        }

        return null;
    }

    @Override
    public Map<String, Integer> getOrgDataCount(Map<String, Object> params) {
        return organizationMapper.getOrgDataCount(params);
    }

    @Override
    public Map<String, Object> getOrganizationCount() {
        return organizationMapper.getOrganizationCount();
    }
}
